using System;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using JMClient.Models.Data;
using JMClient.Models.PhysicalComponents;
using JMClient.Views;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Navigation.Regions;

namespace JMClient.ViewModels;

public class SandboxWindowViewModel : BindableBase, IDialogAware,SandboxDialogWindow.IParameterReceiver
{
    public int DeviceId { get; set; }
    private readonly IRegionManager _regionManager;
    public DialogParameters DialogParameters { get; set; }
    public IRegionManager ScopedRegionManager { get; private set; }
    
    private readonly TaskCompletionSource<object?> _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
    private DialogCloseListener _requestClose;
    public Task Ready => _ready.Task;
    
    private DeviceEntity _device;
    public required DeviceEntity DeviceEntity
    {
        get => _device;
        set => SetProperty(ref _device, value);
    }

    public DelegateCommand CloseCommand { get; }

    public SandboxWindowViewModel(IRegionManager region)
    {

        CloseCommand = new DelegateCommand(LoadRegion);
    }
    
    // 关闭命令：尝试让当前窗口关闭
    public string Title { get; set; } = "沙箱";

    public event Action<IDialogResult>? RequestClose;

    public bool CanCloseDialog() => true;

    public void OnDialogOpened(IDialogParameters parameters)
    {
        DialogParameters = new DialogParameters();
        foreach (var key in parameters.Keys)
        {
            DialogParameters.Add(key, parameters.GetValue<object>(key));
        }
        if (parameters.TryGetValue("entity", out DeviceEntity e))
            DeviceEntity = e;
        if (parameters.TryGetValue("title", out string t))
            Title = t;
        ScopedRegionManager = parameters.GetValue<IRegionManager>("scopedRegionManager");
        ScopedRegionManager.RequestNavigate(DeviceEntity.ModuleRegion,DeviceEntity.ModuleRegion);
    }

    DialogCloseListener IDialogAware.RequestClose => _requestClose;

    public void OnDialogClosed()
    {
        Close();
    }
    public void Close() => RequestClose?.Invoke(new DialogResult(ButtonResult.OK));

    public void LoadRegion()
    {
        ScopedRegionManager.RequestNavigate(DeviceEntity.ModuleRegion,DeviceEntity.ModuleRegion);
    }
}